import { listAppTypeList, removeApp } from '@/services/configserver/api';
import { PlusOutlined } from '@ant-design/icons';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import ProTable, { ActionType, ProColumns } from '@ant-design/pro-table';
import { Button, message } from 'antd';
import React, { useRef, useState } from 'react'
import { FormattedMessage, useIntl } from 'umi';
import styles from './index.less';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAddAppTypeInfo = async (fields: API.AppTypeInfoListItem) => {
    const hide = message.loading('正在添加');
    try {
        // await addApp({ ...fields });
        hide();
        message.success('添加成功');
        console.log('AppsTemplateMgr Event=handleAddAppTypeInfo,value=', fields)
        return true;
    } catch (error) {
        hide();
        message.error('添加失败');
        return false;
    }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param fileds
 */
const handleRemoveAppType = async (fileds: API.AppsInfoListItem) => {
    const hide = message.loading('正在删除');
    console.log('AppsInfoList Event=handleRemoveApp,value=', fileds);

    try {
        await removeApp({
            id: fileds.id,
            hostname: fileds.hostname,
        });
        hide();
        message.success('删除成功');
        return true;
    } catch (error) {
        hide();
        message.error('删除失败');
        return false;
    };
}


const AppsTemplateMgr: React.FC<{}> = () => {
    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<API.AppTypeInfoListItem>();
    const [modalData, setModalData] = useState<API.AppTypeInfoListItem>();
    const [CUAppTypeInfoModalVisible, handleCUAppTypeInfoModalVisible] = useState<boolean>(false);

    const columns: ProColumns<API.AppTypeInfoListItem>[] = [
        {
            title: (
                <FormattedMessage
                    id="pages.listAppTypeInfoTable.id"
                    defaultMessage="ID"
                />
            ),
            dataIndex: 'id',
            tip: '数据库ID',
            search: false,
        },
        {
            title: <FormattedMessage id="pages.listAppTypeInfoTable.apptype" defaultMessage="Apptype" />,
            dataIndex: 'apptype',
            sorter: true,
            valueType: 'textarea',
        },
        {
            title: <FormattedMessage id="pages.listAppTypeInfoTable.image" defaultMessage="Image" />,
            dataIndex: 'image',
            valueType: 'textarea',
        },
        {
            title: <FormattedMessage id="pages.listAppTypeInfoTable.solution" defaultMessage="Solution" />,
            dataIndex: 'solution',
            valueType: 'textarea',
        },
        {
            title: <FormattedMessage id="pages.listAppTypeInfoTable.version" defaultMessage="Version" />,
            dataIndex: 'version',
            valueType: 'textarea',
            search: false,
        },
        {
            title: <FormattedMessage id="pages.listHostsInfoTable.titleOption" defaultMessage="Operating" />,
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="update"
                    onClick={() => {
                        console.log("HostsInfoList 表单: Event=remove.onClick,value=", record);
                        handleCUAppTypeInfoModalVisible(true);
                        setCurrentRow(record);
                    }}
                >
                    <FormattedMessage id="pages.listHostsInfoTable.update" defaultMessage="Update" />
                </a>,
                <a
                    key="remove"
                    onClick={async () => {
                        console.log("HostsInfoList 表单: Event=remove.onClick,value=", record);
                        const success = await handleRemoveAppType(record);
                        if (success) {
                            setCurrentRow(undefined);
                            if (actionRef.current) {
                                actionRef.current.reload();
                            }
                        }
                    }}
                    // onClick={() => {
                    //   handleRemoveHost(record);
                    //   setCurrentRow(record);
                    // }}
                    className={styles.listAppsTypeInfoOperationRemove}
                >
                    <FormattedMessage id="pages.listHostsInfoTable.remove" defaultMessage="Remove" />
                </a>,
            ],
        },
    ];

    return (
        // <PageContainer>
        <>
            <ProTable<API.HostsInfoListItem, API.PageParams>
                headerTitle={intl.formatMessage({
                    id: 'pages.listAppTypeInfoTable.title',
                    defaultMessage: 'Enquiry form',
                })}
                actionRef={actionRef}
                // rowKey表示每一行的key
                rowKey="id"
                search={{
                    // labelWidth: 60,
                    span: 6,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleCUAppTypeInfoModalVisible(true);
                        }}
                    >
                        <PlusOutlined /> <FormattedMessage id="pages.listAppTypeInfoTable.new" defaultMessage="New" />
                    </Button>,
                ]}
                request={listAppTypeList}
                columns={columns}
            />
            {/* Create or Update 更新主机信息 */}
            <ModalForm<{
                id?: number;
                apptype: string;
                image: string;
                solution: string;
                version: string;
            }>
                title={
                    currentRow?.id === undefined
                        ?
                        (intl.formatMessage({
                            id: 'pages.CUAppTypeInfoModal.addtitle',
                            defaultMessage: 'New App',
                        }))
                        :
                        (
                            (intl.formatMessage({
                                id: 'pages.CUAppTypeInfoModal.updatetitle',
                                defaultMessage: 'Update App',
                            }))
                        )
                }
                autoFocusFirstInput
                modalProps={{
                    onCancel: () => {
                        console.log('AppsTemplateMgr event=CUAppTypeInfoModal OnClose');
                        handleCUAppTypeInfoModalVisible(false);
                        setCurrentRow(undefined);
                    },
                    // 需要销毁modal的子元素,否则重新打开的时候 initialValues不会变
                    destroyOnClose: true,
                }}
                // width={800}
                visible={CUAppTypeInfoModalVisible}
                onFinish={async (values) => {
                    console.log('AppsTemplateMgr event=CUAppTypeInfoModal OnFinsh,values=', values);
                    message.success('提交成功');
                    handleCUAppTypeInfoModalVisible(false);
                    setCurrentRow(undefined);
                    return true;
                }}

            >

                <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="id"
                        label="ID"
                        placeholder="请输入ID"
                        // fieldProps={{ value: currentRow?.id || '' }}
                        initialValue={currentRow?.id || ''}
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="apptype"
                        label="模版名称"
                        placeholder="请输入应用模版名称"
                        initialValue={currentRow?.apptype || ''}
                    />

                    <ProFormText
                        width="md"
                        name="solution"
                        label="所属系统"
                        placeholder="请输入所属系统"
                        initialValue={currentRow?.solution || ''}
                    />
                </ProForm.Group>

                <ProForm.Group>
                    <ProFormText
                        width="md"
                        name="image"
                        label="镜像"
                        placeholder="请输入镜像名称"
                        initialValue={currentRow?.image || ''}
                    />

                    <ProFormText
                        width="md"
                        name="version"
                        label="版本"
                        placeholder="请输入版本号"
                        initialValue={currentRow?.version || ''}
                    />
                </ProForm.Group>
            </ModalForm>
        </>
        // </PageContainer>
    );
}

export default AppsTemplateMgr;